import { Component } from '@angular/core';
import { Store } from '@ngrx/store';
import { NzMessageService } from 'ng-zorro-antd/message';
import { SearchResult } from './services/data-types/common.types';
import { User } from './services/data-types/member.type';
import { MemberService } from './services/member.service';
import { SearchService } from './services/search.service';
import { loginParams } from './share/wy-ui/wy-layer/wy-layer-login/wy-layer-login.component';
import { AppStoreModule } from './store';
import { SetModalType, SetUserId } from './store/actions/member.actions';
import { BatchActionsService } from './store/batch-actions.service';
import { ModalTypes } from './store/reducers/member.reducer';
import { codeJson } from './utils/base64';
import { isEmptyObject } from './utils/tools';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.less']
})
export class AppComponent {
  title = 'ng-wyy';
  menu = [{
    label: '发现',
    path: '/home',
  },{
    label: '歌单',
    path: '/sheet',
  }]
  wyRememberLogin!: loginParams;
  searchResult!: SearchResult;
  user!: User;
  ModalTypes = ModalTypes;

  constructor (
    private searchServe: SearchService,
    private store$: Store<AppStoreModule>,
    private batchActionsServe: BatchActionsService,
    private memberServe: MemberService,
    private messageServer: NzMessageService,
  ){
    const userId = localStorage.getItem("wyUserId");
    if(userId){
      this.store$.dispatch(SetUserId({id: userId.toString()}))
      this.memberServe.getUserDetail(userId).subscribe(user=>{ this.user = user })
    }
    const wyRememberLogin = localStorage.getItem("wyRememberLogin");
    if(wyRememberLogin){
      this.wyRememberLogin = JSON.parse(wyRememberLogin)
    }
  }

  // 打开弹窗
  onenModal(type: ModalTypes){
    this.batchActionsServe.controlModal(true, type)
  }

  // 改变弹窗类型
  onChangeModalType( modalType = ModalTypes.Default ){
    this.store$.dispatch(SetModalType({ modalType }))
  }

  onSearch(keywords: string){
    if(keywords){
      this.searchServe.Search(keywords).subscribe(res => {
        this.searchResult = this.highlightkeyword(keywords, res)
      })
    }else{
      this.searchResult = {}
    }
  }

  private highlightkeyword (keywords: string, result: SearchResult): SearchResult{
    if(!isEmptyObject(result)){
      const reg = new RegExp(keywords, 'ig');
      ['artists','playlists','songs'].forEach(type => {
        if(result[type]){
          result[type].forEach((item: any) =>{
            item.name = item.name.replace(reg, '<span class="highlight">$&</span>')
          })
        }
      })
    }
    return result
  }
  // 15079010174
  // LYC6809915TC
  // 登录
  onLogin( params: loginParams){
    this.memberServe.login(params).subscribe(user =>{
      this.user = user;
      this.batchActionsServe.controlModal(false);
      this.alertMessage('success', '登录成功');
      localStorage.setItem("wyUserId",  user.profile.userId.toString())
      this.store$.dispatch(SetUserId({id: user.profile.userId.toString()}))
      if(params.remember){
        localStorage.setItem("wyRememberLogin",  JSON.stringify(codeJson(params)))
      }else{
        localStorage.removeItem('wyRememberLogin')
      }
    },error=>{
      this.alertMessage('error', error.message || '登录失败')
    })
  }

  // 退出登录
  onLogout(){
    this.memberServe.logout().subscribe(res=>{
      let users!: User;
      this.user = users;
      localStorage.removeItem('wyUserId')
      this.store$.dispatch(SetUserId({id: ''}))
      this.alertMessage('error', res.msg || '已退出')
    },error=>{
      this.alertMessage('error', error.message || '退出失败')
    })
  }

  private alertMessage( type: string, msg: string){
    this.messageServer.create(type,msg)
  }

}
